﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using EmoneyWeiXinEntity;

namespace EmoneyWeiXinCommon
{
    public class LoginUserInfo
    {
        public static string key2 = "EmoneyWeiXin.LoginUser.";
        public static string cookieName = "EmoneyWeiXinUserCookie";
        public static string keyguid = "EmoneyWeiXinGuid";
        public static void AddLoginUserCache(string id, Object obj)
        {
            string key = key2 + id;
            MemcachedTools1 cache = new MemcachedTools1();
            cache.Add(key, obj, 4, 0, 0);
        }

        public static void AddLoginUserSave(UserEntity us)
        {
            AddLoginUserCache(us.id.ToString(), us);

            UserEntity usfd = GetLoginUserCache(us.id.ToString());

            setCookie(us.id.ToString());

        }

        public static void deleteUserInfo(string id = "")
        {
            if (string.IsNullOrEmpty(id))
            {
                id = getCookie();
            }
            AddLoginUserCache(id, null);
            setCookie("");
        }


        public static UserEntity GetLoginUserCache(string id = "")
        {
            if (string.IsNullOrEmpty(id))
            {
                id = getCookie();
            }
            string key = key2 + id;
            MemcachedTools1 cache = new MemcachedTools1();
            UserEntity user = cache.Get<UserEntity>(key);
            if (user == null || string.IsNullOrEmpty(user.loginName))
            {
                return new UserEntity();
            }
            return user;
        }

        public static void setCookie(string guid)
        {
            //创建Cookie 并命名
            HttpCookie cookietwo = new HttpCookie(cookieName);
            //   cookietwo.Name = "UserInfo";
            //Cookie为一年有效期
            cookietwo.Expires = DateTime.Today.AddDays(7);
            //设置Cookie对应键值 
            cookietwo.Values[keyguid] = guid;
            //  CookieHelp.CookieHelper.AddCookie(cookietwo);
            // 用Response添加到Cookie中
            HttpContext.Current.Response.Cookies.Add(cookietwo);
        }

        public static string getCookie()
        {
            if (HttpContext.Current.Request.Cookies[cookieName] != null)
            {
                //读取Cookie 键值
                return HttpContext.Current.Request.Cookies[cookieName][keyguid].ToString();
            }
            return "";
        }
    }
}
